//
//  TTKUtil.m
//  AQUA
//
//  Created by 吕清毅 on 2018/8/1.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "TTKUtil.h"

@implementation TTKUtil

/**
 获取AppDelegate
 */
+ (AppDelegate *)getAppDelegate{
    AppDelegate *delegates = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegates;
}

+ (MBProgressHUD *)createMbprogressHudWith:(UIViewController *)VC
{
    MBProgressHUD  *HUD = [MBProgressHUD showHUDAddedTo:VC.view animated:YES];
    HUD.contentColor=[UIColor whiteColor];
    HUD.bezelView.color=[UIColor blackColor];
    HUD.mode = MBProgressHUDModeIndeterminate;
    HUD.label.text= @"加载中";
    HUD.removeFromSuperViewOnHide=YES;
    [VC.view addSubview:HUD];
    [HUD showAnimated:YES];
    //3,设置背景框的圆角值，默认是10
    HUD.bezelView.layer.cornerRadius = 10.0;
    HUD.bezelView.layer.masksToBounds = YES;
    //4,设置提示信息 信息颜色，字体
    HUD.label.font = FontWithSize(15);
    //10，设置各个元素距离矩形边框的距离
    HUD.margin = 0;
    //11，背景框的最小大小
    HUD.minSize = CGSizeMake(80,80);
    //14,设置显示和隐藏动画类型  有三种动画效果，如下
    HUD.animationType = MBProgressHUDAnimationFade; //和上一个相反，前近，最后淡化消失
    return HUD;
}

+ (void)hudShowMessage:(NSString *)message
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.bezelView.backgroundColor = UIColorFromHex(0xFF9D9D9D);
    hud.contentColor = [UIColor whiteColor];
    hud.label.text =NSLocalizedString(message, nil);
    hud.label.font = FontWithSize(12);
    [hud hideAnimated:YES afterDelay:HUDTime];
}

+ (NSString*)stringReplaceWith:(NSString *)str
{
    NSString *replacedStr = [str stringByReplacingOccurrencesOfString:@"+"withString:@"00"];
    NSLog(@"replacedStr ==== %@", replacedStr);
    return replacedStr;
}

+ (NSString *)getCurrentLanguage
{
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    NSLog( @"当前语言%@" , currentLanguage);
    return currentLanguage;
}

+ (NSString *)getToday
{
    NSDate *date=[NSDate date];
    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"MM月dd"];
    NSString *dateStr;
    dateStr=[format1 stringFromDate:date];
    NSLog(@"%@",dateStr);
    return dateStr;
}

+ (NSString *)getSubToString:(NSString *)str andIndex:(int)index
{
    NSString *str1 = [str substringToIndex:index];//截取掉下标5之前的字符串
    NSLog(@"截取的值为：%@",str1);
    return str1;
}

+ (NSString *)getSubFromString:(NSString *)str andIndex:(int)index
{
     NSString *str2 = [str substringFromIndex:index];//截取掉下标3之后的字符串
    NSLog(@"截取的值为：%@",str2);
    return str2;
}

+ (void)setAutomaticallyAdjustsScrollViewInsetsWidth:(UITableView *)tableView withView:(UIViewController *)view
{
    //NSString *version = [UIDevice currentDevice].systemVersion;
    if (@available(iOS 11.0, *))
    {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else
    {
        view.automaticallyAdjustsScrollViewInsets = NO;
    }
}

+ (void)setCAGradientLayer:(UIView *)view From:(UIColor *)fromColor To:(UIColor *)toColor
{
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = view.bounds;
    gradient.colors = [NSArray arrayWithObjects:
                       (id)fromColor.CGColor,
                       (id)toColor.CGColor,nil];
    [view.layer addSublayer:gradient];
    
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    gradientLayer.colors = @[(__bridge id)fromColor.CGColor, (__bridge id)toColor.CGColor];
//    gradientLayer.locations = @[@0.3, @1.0];
//    gradientLayer.startPoint = CGPointMake(0, 0);
//    gradientLayer.endPoint = CGPointMake(1.0, 0);
//    gradientLayer.frame = view.bounds;
//    [view.layer addSublayer:gradientLayer];
}

+ (UIImage *)becomeGrayColorWith:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (NSString *)nowLanguage
{
    NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *languageName = [appLanguages objectAtIndex:0];
    NSLog(@"language:%@",languageName);
    return languageName;
}

+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间
    NSString *currentDate = [formatter stringFromDate:datenow];
    return currentDate;
}

+(NSAttributedString*)getAtttributeStringWithLineSpace:(CGFloat)lineSpace kern:(CGFloat)kern and:(NSString *)title
{
    //调整行间距
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = lineSpace;
    NSDictionary *attriDict =@{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@(kern)};
    NSMutableAttributedString*attributedString = [[NSMutableAttributedString alloc]initWithString:title attributes:attriDict];
    return attributedString;
}

+(NSAttributedString*)getAtttributeStringColorWithLineSpace:(CGFloat)lineSpace kern:(CGFloat)kern and:(NSString *)title
{
    //调整行间距
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = lineSpace;
    NSDictionary *attriDict =@{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@(kern),NSForegroundColorAttributeName:UIColorFromHex(0x8D8D8D)};
    NSMutableAttributedString*attributedString = [[NSMutableAttributedString alloc]initWithString:title attributes:attriDict];
    return attributedString;
}

+(NSAttributedString*)getAtttributeStringWithLineSpace:(CGFloat)lineSpace kern:(CGFloat)kern and:(NSString *)title andColor:(UIColor *)color
{
    //调整行间距
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = lineSpace;
    NSDictionary *attriDict =@{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@(kern),NSForegroundColorAttributeName:color};
    NSMutableAttributedString*attributedString = [[NSMutableAttributedString alloc]initWithString:title attributes:attriDict];
    return attributedString;
}

//根据高度获取宽度
+ (CGSize)sizeWithText:(NSString *)text Height:(CGFloat)height Font:(UIFont*)font
{
    CGSize size = CGSizeMake(CGFLOAT_MAX,height);
    size = [text boundingRectWithSize:size options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size;
    return size;
}

//根据宽度获取高度
+ (CGSize)sizeWithText:(NSString *)text Width:(CGFloat)width Font:(UIFont*)font
{
    CGSize size = CGSizeMake(width,CGFLOAT_MAX);
    size = [text boundingRectWithSize:size options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size;
    return size;
}

+ (BOOL)isNil:(id)str
{
    if ( [str isEqual:[NSNull null]] || str == nil) {
        return YES;
    }else{
        if ([str isEqual:[NSString string]]) {
            if ([str isEqualToString:@""]) {
                return YES;
            }
        }
        return NO;
    }
}

+ (void)alertControllerShowMsg:(NSString *)msg and:(UIViewController*)vc
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action2];
    [vc presentViewController:alert animated:YES completion:nil];
}

+(NSString*)encodeString:(NSString*)unencodedString
{
    if([[[UIDevice currentDevice]systemVersion]floatValue] >=9.0)
    {
        return[unencodedString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
    }
    NSString*encodedString = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)unencodedString,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
    return encodedString;
}

//是否开启通知
+ (BOOL)isOpenNotify
{
    if ([[UIApplication sharedApplication] currentUserNotificationSettings].types  == UIRemoteNotificationTypeNone) {
        return NO;
    }else {
        return YES;
    }
}

/**  压缩图片*/
+ (UIImage *)imageWithOriginalImage:(UIImage *)image{
    // 宽高比
    CGFloat ratio = image.size.width/image.size.height;
    // 目标大小
    CGFloat targetW = 1280;
    CGFloat targetH = 1280;
    
    // 宽高均 <= 1280，图片尺寸大小保持不变
    if (image.size.width<1280 && image.size.height<1280) {
        return image;
    }
    // 宽高均 > 1280 && 宽高比 > 2，
    else if (image.size.width>1280 && image.size.height>1280){
        
        // 宽大于高 取较小值(高)等于1280，较大值等比例压缩
        if (ratio>1) {
            targetH = 1280;
            targetW = targetH * ratio;
        }
        // 高大于宽 取较小值(宽)等于1280，较大值等比例压缩 (宽高比在0.5到2之间 )
        else{
            targetW = 1280;
            targetH = targetW / ratio;
        }
        
    }
    // 宽或高 > 1280
    else{
        // 宽图 图片尺寸大小保持不变
        if (ratio>2) {
            targetW = image.size.width;
            targetH = image.size.height;
        }
        // 长图 图片尺寸大小保持不变
        else if (ratio<0.5){
            targetW = image.size.width;
            targetH = image.size.height;
        }
        // 宽大于高 取较大值(宽)等于1280，较小值等比例压缩
        else if (ratio>1){
            targetW = 1280;
            targetH = targetW / ratio;
        }
        // 高大于宽 取较大值(高)等于1280，较小值等比例压缩
        else{
            targetH = 1280;
            targetW = targetH * ratio;
        }
    }
    // 注：这些方法是NSUtil这个工具类里的
   image = [TTKUtil imageCompressWithImage:image targetHeight:targetH targetWidth:targetW];
    return image;
}


/**  重绘*/
+ (UIImage *)imageCompressWithImage:(UIImage *)sourceImage targetHeight:(CGFloat)targetHeight targetWidth:(CGFloat)targetWidth
{
    //    CGFloat targetHeight = (targetWidth / sourceImage.size.width) * sourceImage.size.height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
@end
